package com.le.tester.imooc.masterJUC.collections.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 描述：array blocking queue demo
 */
public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        //队列的容量是三个
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        Interviewer interviewer = new Interviewer(queue);
        Customer customer = new Customer(queue);
        new Thread(interviewer).start();
        new Thread(customer).start();
    }
}

class Interviewer implements Runnable {

    private BlockingQueue<String> queue;

    public Interviewer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("10个候选人都来了");
        String candidate;
        for (int i = 0; i < 10; i++) {
            candidate = "Candidate:" + i;
            try {
                queue.put(candidate);
                System.out.println("安排好了：" + candidate);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        //最后放进结束的标识
        try {
            queue.put("stop");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}

class Customer implements Runnable {

    private BlockingQueue<String> queue;

    public Customer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String msg = null;
        try {
            while (!(msg = queue.take()).equals("stop")) {
                System.out.println(msg + ":到了");
            }
            System.out.println("所有候选人都结束了");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
